// 图片上传工具
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 确保上传目录存在
const ensureDir = (dirPath) => {
  if (!fs.existsSync(dirPath)) {
    fs.mkdirSync(dirPath, { recursive: true });
  }
};

// 创建上传目录（相对于server目录）
const uploadsDir = path.join(__dirname, '../../uploads');
const productsDir = path.join(uploadsDir, 'products');
const avatarsDir = path.join(uploadsDir, 'avatars');
const categoriesDir = path.join(uploadsDir, 'categories');

ensureDir(uploadsDir);
ensureDir(productsDir);
ensureDir(avatarsDir);
ensureDir(categoriesDir);

// 配置存储
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    let uploadPath = productsDir;
    
    // 根据上传类型选择目录
    if (req.body.uploadType === 'avatar') {
      uploadPath = avatarsDir;
    } else if (req.body.uploadType === 'category') {
      uploadPath = categoriesDir;
    }
    
    cb(null, uploadPath);
  },
  filename: function (req, file, cb) {
    // 生成唯一文件名：时间戳-随机数-原文件名
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    const ext = path.extname(file.originalname);
    const name = path.basename(file.originalname, ext);
    cb(null, `${name}-${uniqueSuffix}${ext}`);
  }
});

// 文件过滤器（支持图片和视频）
const fileFilter = (req, file, cb) => {
  // 允许的图片和视频格式
  const allowedTypes = /jpeg|jpg|png|gif|webp|mp4|webm|ogg|mov|avi/;
  const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
  const mimetype = allowedTypes.test(file.mimetype) || file.mimetype.startsWith('image/') || file.mimetype.startsWith('video/');

  if (mimetype && extname) {
    return cb(null, true);
  } else {
    cb(new Error('只支持图片格式：jpg, jpeg, png, gif, webp 和视频格式：mp4, webm, ogg, mov, avi'));
  }
};

// 配置multer
const upload = multer({
  storage: storage,
  limits: {
    fileSize: 50 * 1024 * 1024 // 50MB（支持较大图片和视频）
  },
  fileFilter: fileFilter
});

// 导出上传中间件
module.exports = {
  // 商品图片上传（单文件）
  uploadProductImage: upload.single('image'),
  
  // 商品图片/视频上传（多文件，最多10个）
  uploadProductImages: upload.array('images', 10),
  
  // 用户头像上传
  uploadAvatar: upload.single('avatar'),
  
  // 分类图标上传
  uploadCategoryIcon: upload.single('icon'),
  
  // 通用上传（根据uploadType参数）
  uploadFile: upload.single('file'),
  
  // 获取图片URL
  getImageUrl: (filename, type = 'products') => {
    const baseUrl = process.env.SERVER_URL || process.env.HTTPS_URL || 'https://127.0.0.1';
    return `${baseUrl}/uploads/${type}/${filename}`;
  }
};

